#include "qlog.h"

#include <QFile>
#include <QDir>
#include <QScopedPointer>
#include <QTextStream>
#include <QDateTime>
#include <QLoggingCategory>

const static QString LOG_FOLDER = "logs";
static QScopedPointer<QFile> m_logFile;
static QString log_file_name = "log";

void logInit(void) {
    QDir dir(LOG_FOLDER);
    if(!dir.exists()) {
        QDir().mkdir(LOG_FOLDER);
    }
}

static bool checkLogFile(void) {
    QDateTime time = QDateTime::currentDateTime();
    QString log_time = time.toString("yyyyMMdd");
    if(QString::compare(log_time, log_file_name) == 0) {
        return true;
    }
    log_file_name = log_time;
    QString logPath = LOG_FOLDER + "/" + log_file_name + ".log";
    m_logFile.reset(new QFile(logPath));
    m_logFile.data()->open(QFile::Append | QFile::Text);
    return false;
}

void logReHandle(QtMsgType type, const QMessageLogContext &context, const QString &msg) {
    checkLogFile();
    // Open stream file writes
    QTextStream out(m_logFile.data());
    // Write the date of recording
    out << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz ");
    // By type determine to what level belongs message
    switch (type) {
        case QtInfoMsg:     out << "INF "; break;
        case QtDebugMsg:    out << "DBG "; break;
        case QtWarningMsg:  out << "WRN "; break;
        case QtCriticalMsg: out << "CRT "; break;
        case QtFatalMsg:    out << "FTL "; break;
    }
    // Write to the output category of the message and the message itself
    out << context.category << ": "
        << msg << endl;
    out.flush();    // Clear the buffered data
}
